# -*- coding: utf-8 -*-
"""
Yelp Fusion API code sample.
This program demonstrates the capability of the Yelp Fusion API
by using the Search API to query for businesses by a search term and location,
and the Business API to query additional information about the top result
from the search query.
Please refer to http://www.yelp.com/developers/v3/documentation for the API
documentation.
This program requires the Python requests library, which you can install via:
`pip install -r requirements.txt`.
Sample usage of the program:
`python yelp_api.py --term="bars" --location="San Francisco, CA"`
"""
from __future__ import print_function

import argparse
import json
import pprint
import requests
import sys
import urllib
import boto3
from decimal import Decimal
import datetime

# This client code can run on Python 2.x or 3.x.  Your imports can be
# simpler if you only need one of those.
try:
    # For Python 3.0 and later
    from urllib.error import HTTPError
    from urllib.parse import quote
    from urllib.parse import urlencode
except ImportError:
    # Fall back to Python 2's urllib2 and urllib
    from urllib2 import HTTPError
    from urllib import quote
    from urllib import urlencode


# Yelp Fusion no longer uses OAuth as of December 7, 2017.
# You no longer need to provide Client ID to fetch Data
# It now uses private keys to authenticate requests (API Key)
# You can find it on
# https://www.yelp.com/developers/v3/manage_app
API_KEY = "f8rvhi09S9Kl88Na8yih3TMTkXIPmJL_s-yP5D8LN4FJnVRrQDWXuT24OkffR3cGbJX7jJrTVktaMrgKwXNDEBHujfnjMFPwYf1dJ7NQ-XzNmwK2LahG6QLewQNfXnYx"


# API constants, you shouldn't have to change these.
API_HOST = 'https://api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/'  # Business ID will come after slash.


# Defaults for our simple example.
SEARCH_LIMIT = 50
OFFSET = 0


def request(host, path, api_key, url_params=None):
    """Given your API_KEY, send a GET request to the API.
    Args:
        host (str): The domain host of the API.
        path (str): The path of the API after the domain.
        API_KEY (str): Your API Key.
        url_params (dict): An optional set of query parameters in the request.
    Returns:
        dict: The JSON response from the request.
    Raises:
        HTTPError: An error occurs from the HTTP request.
    """
    url_params = url_params or {}
    url = '{0}{1}'.format(host, quote(path.encode('utf8')))
    headers = {
        'Authorization': 'Bearer %s' % api_key,
    }

    print(u'Querying {0} ...'.format(url))

    response = requests.request('GET', url, headers=headers, params=url_params)

    return response.json()


def search(api_key, term, location, search_limit, offset):
    """Query the Search API by a search term and location.
    Args:
        term (str): The search term passed to the API.
        location (str): The search location passed to the API.
    Returns:
        dict: The JSON response from the request.
    """

    url_params = {
        'term': term.replace(' ', '+'),
        'location': location.replace(' ', '+'),
        'limit': search_limit,
        'offset': offset
    }
    return request(API_HOST, SEARCH_PATH, api_key, url_params=url_params)


def query_api(term, location, search_limit, offset):
    """Queries the API by the input values from the user.
    Args:
        term (str): The search term to query.
        location (str): The location of the business to query.
    """
    response = search(API_KEY, term, location, search_limit, offset)

    businesses = response.get('businesses')

    if not businesses:
        print(u'No businesses for {0} in {1} found.'.format(term, location))
        return

    return businesses


def get_business(api_key, business_id):
    """Query the Business API by a business ID.
    Args:
        business_id (str): The ID of the business to query.
    Returns:
        dict: The JSON response from the request.
    """
    business_path = BUSINESS_PATH + business_id

    return request(API_HOST, business_path, api_key)


def put_data(data):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('yelp-restaurants')
    id=0
    for e in data:
        # print(e)
        time_stamp = datetime.datetime.now()
        time_stamp = time_stamp.strftime('%m/%d/%Y-%H:%M:%S')
        latitude = e['coordinates']['latitude']
        longitude = e['coordinates']['longitude']
        table.put_item(Item={'id':id,'business_id':e['id'],'name':e['name'],'zipcode':e['location']['zip_code'],'rating':Decimal(e['rating']),
            'number_of_reviews':int(e['review_count']),'address':e['location']['address1'],
        'coordinates':f'({latitude}, {longitude})','insertedAtTimestamp':time_stamp, 'cuisine':e['cuisine']})
        id+=1
    print('put success')


def main():

    try:
        myset = set()
        search_limit = 50
        cuisines = ['Italian','Mexican','Burgers','Chinese','Japanese','Thai']
        results = []
        for c in cuisines:
            offset = 0
            for _ in range(20):
                data = query_api(c, 'Manhattan', search_limit, offset)
                for e in data:
                    if e['id'] not in myset:
                        myset.add(e['id'])
                        e['cuisine'] = c
                        results.append(e)
                offset += search_limit
        print(len(myset),len(results))

        put_data(results)


    except HTTPError as error:
        sys.exit(
            'Encountered HTTP error {0} on {1}:\n {2}\nAbort program.'.format(
                error.code,
                error.url,
                error.read(),
            )
        )


if __name__ == '__main__':
    main()